package org.microblog.service.impl;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.microblog.dao.UserDao;
import org.microblog.dao.impl.UserDaoImpl;
import org.microblog.entity.User;
import org.microblog.service.UserService;
import org.microblog.util.DatabaseUtil;
import org.microblog.util.SessionFatoryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;
@Service("userService")
public class UserServiceImpl implements UserService {
    //SqlSessionFactory sessionFactory = SessionFatoryUtil.sessionFactory;
    @Autowired
    private UserDao userDao;// = sqlSession.getMapper(UserDao.class);

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public User findUser(String uId, String password) throws SQLException {
        //SqlSession sqlSession = sessionFactory.openSession();

        User tmp = userDao.findUser(uId, password);
        //sqlSession.commit();
        //sqlSession.close();
        return tmp;
    }

    @Override
    public int updateUser(User user) throws SQLException {
//        Connection conn = null;
//        try{
//            conn = DatabaseUtil.getConnection();
//            return new UserDaoImpl(conn).updateUser(user);
//        }catch(SQLException e){
//            e.printStackTrace();
//            throw e;
//        }finally {
//            DatabaseUtil.closeAll(conn,null,null);
//        }
      int ret=userDao.updateUser(user);

        return ret;
    }

    @Override
    public boolean findUser(String uId) throws SQLException {
        //SqlSession sqlSession=sessionFactory.openSession(true);
       // UserDao userDao=sqlSession.getMapper(UserDao.class);
        int ret=userDao.findUserByid(uId);
        //sqlSession.commit();
        //sqlSession.close();
        if (ret>0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public int register(User user) throws SQLException {
        Connection conn = null;
        int result = 0;
        try {
            conn = DatabaseUtil.getConnection();
            conn.setAutoCommit(false);
            UserDao userDao = new UserDaoImpl(conn);
            if(userDao.findUserByid(user.getUserId())==0){
                result = userDao.register(user);
            }else{
                result = -1;
            }
            //conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();

        } finally {
            DatabaseUtil.closeAll(conn, null, null);
        }
        return result;
    }
}
